package com.zhuhjay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.mapper.SystemUserMapper;
import com.zhuhjay.model.dto.UserRegisterDto;
import com.zhuhjay.model.entity.SystemUser;
import com.zhuhjay.security.LoginUserDetail;
import com.zhuhjay.service.SystemUserService;
import com.zhuhjay.utils.result.Result;
import com.zhuhjay.utils.result.ResultBean;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zhuhjay
 * @since 2023-01-11
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser>
        implements SystemUserService, UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    /** 登录时获取数据库中用户的信息 **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        SystemUser user = this.lambdaQuery()
                .eq(SystemUser::getUsername, username).one();
        // 检查有效性
        if (user == null) {
            // 如果使用 UsernameNotFoundException，SpringSecurity 将会隐藏该错误信息，打印 "用户名或密码错误"
            throw new InternalAuthenticationServiceException("登录用户: {" + username + "} 不存在");
        }
        if (user.getStatus() == 0) {
            throw new InternalAuthenticationServiceException("登录用户: {" + username + "} 已被停用");
        }
        // 权限列表
        List<String> permissions = new ArrayList<>();
        permissions.add("ROLE_USER");
        return new LoginUserDetail(user, permissions);
    }

    @Override
    public Result register(UserRegisterDto userRegister) {
        // 用户名不能重复
        Long count = this.lambdaQuery()
                .eq(SystemUser::getUsername, userRegister.getUsername()).count();
        if (count == null || count != 0) {
            return ResultBean.fail("该用户名已注册");
        }
        // 进行密码加密
        userRegister.setPassword(passwordEncoder.encode(userRegister.getPassword()));
        SystemUser user = new SystemUser();
        BeanUtil.copyProperties(userRegister, user);
        user.setNickName("系统用户-" + IdUtil.nanoId());
        boolean save = this.save(user);
        return save ? ResultBean.ok() : ResultBean.fail("注册失败，请重试");
    }
}
